import axios from 'axios'
import store from '~/store'
import router from '~/router'
import {MessageBox,Notification } from 'element-ui'
import i18n from '~/plugins/i18n'


axios.defaults.timeout = 30000;
// Request interceptor
axios.interceptors.request.use(request => {
  const token = store.getters['auth/token']
  if (token) {
    request.headers.common['Authorization'] = `Bearer ${token}`
  }

  const locale = store.getters['lang/locale']
  if (locale) {
    request.headers.common['Accept-Language'] = locale
  }

  // request.headers['X-Socket-Id'] = Echo.socketId()

  return request
})

// Response interceptor
axios.interceptors.response.use(response => response, error => {
  const { status } = error.response
  const { data } = error.response
  console.log(data)
  if (status >= 500) {
      let message = data.msg ? data.msg : data.message
      MessageBox(message ? message : i18n.t('error_alert_text'), i18n.t('error_alert_title'), {
          confirmButtonText: '确定',
          callback: action => {
          }
      });
  }
  if(status === 422){
    let valid = data.errors
    Object.keys(valid).forEach(val => {
      console.log(valid[val])
      Notification.error({
        title:'字段校验',
        message:valid[val].join(',')
      })
    });
    //Notify
  }

  if (status === 401 && store.getters['auth/check']) {
      MessageBox(i18n.t('token_expired_alert_text'), i18n.t('token_expired_alert_title'), {
          confirmButtonText: i18n.t('ok'),
          cancelButtonText: i18n.t('cancel'),
          type: 'warning'
      }).then(() => {
          store.commit('auth/LOGOUT')

          router.push({ name: 'login' })
      });
  }

  return Promise.reject(error)
})
